<script setup lang="ts">
import type { InputNumberBoxEvent } from '@/components/vk-data-input-number-box/vk-data-input-number-box'
import { useGuessList } from '@/composables'
import { getCartListAPI, removeCartAPI, selectCartAPI, updateCartAPI } from '@/services/cart'
import { useMemberStore } from '@/stores'
import type { CartItem } from '@/types/car'
import { onShow } from '@dcloudio/uni-app'

import { computed, ref } from 'vue'

const memberStore = useMemberStore()
//获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

const cartListData = ref<CartItem[]>([])
//获取购物车列表
const getCartList = async () => {
  const res = await getCartListAPI()
  cartListData.value = res.result
}
onShow(() => {
  //登录的情况下，才去调用接口
  if (memberStore.profile) {
    getCartList()
  }
})

//使用vue 的 计算属性，来动态计算是否能全选按钮选中状态
const isAllChecked = computed<boolean>(() => {
  return cartListData.value.length > 0 && cartListData.value.every((item) => item.selected)
})

//使用vue的计算属性，计算选中的总和
const selectPrices = computed<string>(() => {
  return cartListData.value
    .filter((item) => item.selected)
    .reduce((sunPrice, item) => {
      //sunPrice表示返回的结果，item表示遍历的元素
      return sunPrice + item.price * item.count
    }, 0)
    .toFixed(2)
  //toFixed(2)表示保留两位小数
})

//使用vue的计算属性，计算商品的件数
const selectCount = computed(() => {
  return cartListData.value
    .filter((item) => item.selected)
    .reduce((sumCount, item) => {
      return sumCount + item.count
    }, 0)
})
//点击全选按钮
const onClickAllSelect = async (isAllChecked: boolean) => {
  //先修改前端按钮选中状态  再去调用接口 修改数据库数据
  const _isSelectAll = !isAllChecked
  cartListData.value.forEach((item) => {
    item.selected = _isSelectAll
  })
  const res = await selectCartAPI(!isAllChecked)
  // await getCartList()
}

//点击商品选中按钮
const onItemSelected = async (item: CartItem) => {
  //先修改前端按钮选中状态  再去调用接口 修改数据库数据
  item.selected = !item.selected
  const res = await updateCartAPI(item.skuId, { selected: item.selected })

  //优化：避免了多次调用接口
  // await getCartList()
}

//商品数量操作参数枚举
enum QuantityAction {
  //减少
  DECREASE = 'decrease',
  //新增
  INCREASE = 'increase',
}

//点击商品数量操作
const onClickCount = async (skuId: string, option: QuantityAction, count: number) => {
  if (!skuId) {
    uni.showToast({
      title: '请选择商品在进行操作',
      icon: 'none',
    })
    return
  }
  //表示减少库存
  if (option === QuantityAction.DECREASE) {
    count--
  }
  //表示增加库存
  if (option === QuantityAction.INCREASE) {
    count++
  }
  //判断count是否为0了，如果为0 需要删除该商品信息
  if (count == 0) {
    uni.showModal({
      title: '提示',
      content: '是否将该商品移出购物车？',
      success: async (res) => {
        if (res.confirm) {
          //删除商品信息
          let ids: string[] = []
          ids.push(skuId)
          await removeCartAPI(ids)
          getCartList()
        }
      },
    })
  } else {
    //不为0，调用请求修改库存数据
    const res = await updateCartAPI(skuId, { count })
    getCartList()
  }
}

//改变输入框数据事件
const onChangeCount = async (ev: InputNumberBoxEvent) => {
  if (!ev.index) {
    uni.showToast({
      title: '请选择商品在进行操作',
      icon: 'none',
    })
    return
  }

  //判断count是否为0了，如果为0 需要删除该商品信息
  if (ev.value == 0) {
    uni.showModal({
      title: '提示',
      content: '是否将该商品移出购物车？',
      success: async (res) => {
        if (res.confirm) {
          //删除商品信息
          let ids: string[] = []
          ids.push(ev.index)
          await removeCartAPI(ids)
          getCartList()
        }
      },
    })
  } else {
    let count = ev.value
    //不为0，调用请求修改库存数据
    const res = await updateCartAPI(ev.index, { count })
    getCartList()
  }
}

//删除商品信息
const deleteCartItem = (skuId: string) => {
  uni.showModal({
    title: '提示',
    content: '是否将该商品移出购物车？',
    success: async (res) => {
      if (res.confirm) {
        //删除商品信息
        let ids: string[] = []
        ids.push(skuId)
        await removeCartAPI(ids)
        getCartList()
      }
    },
  })
}
//通过组合式Api来调用封装的主键滑动渲染数据
const { guessRef, onScrolltolower } = useGuessList()

//去结算事件
const goToPayment = () => {
  if (selectCount.value == 0) {
    return uni.showToast({
      title: '请选择商品在进行操作',
      icon: 'none',
    })
  }

  //如果有商品选中，跳转到提示页面
  uni.navigateTo({
    url: '/pagesOrder/create/create',
  })
}
</script>

<template>
  <scroll-view @scrolltolower="onScrolltolower" scroll-y class="scroll-view">
    <!-- 已登录: 显示购物车 -->
    <template v-if="true">
      <!-- 购物车列表 -->
      <view class="cart-list" v-if="memberStore.profile">
        <!-- 优惠提示 -->
        <view class="tips">
          <text class="label">满减</text>
          <text class="desc">满1件, 即可享受9折优惠</text>
        </view>
        <!-- 滑动操作分区 -->
        <uni-swipe-action>
          <!-- 滑动操作项 -->
          <uni-swipe-action-item v-for="item in cartListData" :key="item.skuId" class="cart-swipe">
            <!-- 商品信息 -->
            <view class="goods">
              <!-- 选中状态 -->
              <text
                class="checkbox"
                @tap="onItemSelected(item)"
                :class="{ checked: item.selected }"
              ></text>
              <navigator
                :url="`/pages/goods/goods?id=${item.id}`"
                hover-class="none"
                class="navigator"
              >
                <image mode="aspectFill" class="picture" :src="item.picture"></image>
                <view class="meta">
                  <!-- 如果显示太长，优化一下 -->
                  <view class="name ellipsis">{{ item.name }}</view>
                  <view class="attrsText ellipsis">{{
                    item.specs.map((spec) => spec.valueName).join(' ')
                  }}</view>
                  <view class="price">{{ item.price }}</view>
                </view>
              </navigator>
              <!-- 商品数量 -->
              <view class="count">
                <vk-data-input-number-box
                  v-model="item.count"
                  :min="1"
                  :max="item.stock"
                  :index="item.skuId"
                  @change="onChangeCount"
                />
              </view>
            </view>
            <!-- 右侧删除按钮 -->
            <template #right>
              <view class="cart-swipe-right">
                <button class="button delete-button" @tap="deleteCartItem(item.skuId)">删除</button>
              </view>
            </template>
          </uni-swipe-action-item>
        </uni-swipe-action>
      </view>
      <!-- 购物车空状态 -->
      <view class="cart-blank" v-else>
        <image src="/static/images/blank_cart.png" class="image" />
        <text class="text">购物车还是空的，快来挑选好货吧</text>
        <navigator open-type="switchTab" url="/pages/index/index" hover-class="none">
          <button class="button">去首页看看</button>
        </navigator>
      </view>
      <!-- 吸底工具栏 -->
      <view class="toolbar" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
        <text class="all" @tap="onClickAllSelect(isAllChecked)" :class="{ checked: isAllChecked }"
          >全选</text
        >
        <text class="text">合计:</text>
        <text class="amount">{{ selectPrices }}</text>
        <view class="button-grounp">
          <view
            class="button payment-button"
            @tap="goToPayment"
            :class="{ disabled: selectPrices == '0.00' }"
          >
            去结算({{ selectCount }})
          </view>
        </view>
      </view>
    </template>
    <!-- 未登录: 提示登录 -->
    <view class="login-blank" v-else>
      <text class="text">登录后可查看购物车中的商品</text>
      <navigator url="/pages/login/login" hover-class="none">
        <button class="button">去登录</button>
      </navigator>
    </view>
    <!-- 猜你喜欢 -->
    <ZyGuess ref="guessRef"></ZyGuess>
    <!-- 底部占位空盒子  需要适配安全区 -->
    <view class="toolbar-height"></view>
  </scroll-view>
</template>

<style lang="scss">
// 根元素
:host {
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background-color: #f7f7f8;
}

// 滚动容器
.scroll-view {
  flex: 1;
}

// 购物车列表
.cart-list {
  padding: 0 20rpx;

  // 优惠提示
  .tips {
    display: flex;
    align-items: center;
    line-height: 1;
    margin: 30rpx 10rpx;
    font-size: 26rpx;
    color: #666;

    .label {
      color: #fff;
      padding: 7rpx 15rpx 5rpx;
      border-radius: 4rpx;
      font-size: 24rpx;
      background-color: #27ba9b;
      margin-right: 10rpx;
    }
  }

  // 购物车商品
  .goods {
    display: flex;
    padding: 20rpx 20rpx 20rpx 80rpx;
    border-radius: 10rpx;
    background-color: #fff;
    position: relative;

    .navigator {
      display: flex;
    }

    .checkbox {
      position: absolute;
      top: 0;
      left: 0;

      display: flex;
      align-items: center;
      justify-content: center;
      width: 80rpx;
      height: 100%;

      &::before {
        content: '\e6cd';
        font-family: 'erabbit' !important;
        font-size: 40rpx;
        color: #444;
      }

      &.checked::before {
        content: '\e6cc';
        color: #27ba9b;
      }
    }

    .picture {
      width: 170rpx;
      height: 170rpx;
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      margin-left: 20rpx;
    }

    .name {
      height: 72rpx;
      font-size: 26rpx;
      color: #444;
      //设置文本溢出显示省略号
      // display: inline-block;
      // white-space: nowrap;
      // overflow: hidden;
      // text-overflow: ellipsis;
    }

    .attrsText {
      line-height: 1.8;
      padding: 0 15rpx;
      font-size: 24rpx;
      align-self: flex-start;
      border-radius: 4rpx;
      color: #888;
      background-color: #f7f7f8;
    }

    .price {
      line-height: 1;
      font-size: 26rpx;
      color: #444;
      margin-bottom: 2rpx;
      color: #cf4444;

      &::before {
        content: '￥';
        font-size: 80%;
      }
    }

    // 商品数量
    .count {
      position: absolute;
      bottom: 20rpx;
      right: 5rpx;

      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 220rpx;
      height: 48rpx;

      .text {
        height: 100%;
        padding: 0 20rpx;
        font-size: 32rpx;
        color: #444;
      }

      .input {
        height: 100%;
        text-align: center;
        border-radius: 4rpx;
        font-size: 24rpx;
        color: #444;
        background-color: #f6f6f6;
      }
    }
  }

  .cart-swipe {
    display: block;
    margin: 20rpx 0;
  }

  .cart-swipe-right {
    display: flex;
    height: 100%;

    .button {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 50px;
      padding: 6px;
      line-height: 1.5;
      color: #fff;
      font-size: 26rpx;
      border-radius: 0;
    }

    .delete-button {
      background-color: #cf4444;
    }
  }
}

// 空状态
.cart-blank,
.login-blank {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  height: 60vh;
  .image {
    width: 400rpx;
    height: 281rpx;
  }
  .text {
    color: #444;
    font-size: 26rpx;
    margin: 20rpx 0;
  }
  .button {
    width: 240rpx !important;
    height: 60rpx;
    line-height: 60rpx;
    margin-top: 20rpx;
    font-size: 26rpx;
    border-radius: 60rpx;
    color: #fff;
    background-color: #27ba9b;
  }
}

// 吸底工具栏
.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: var(--window-bottom);
  z-index: 1;

  height: 100rpx;
  padding: 0 20rpx;
  display: flex;
  align-items: center;
  border-top: 1rpx solid #ededed;
  border-bottom: 1rpx solid #ededed;
  background-color: #fff;
  box-sizing: content-box;

  .all {
    margin-left: 25rpx;
    font-size: 14px;
    color: #444;
    display: flex;
    align-items: center;
  }

  .all::before {
    font-family: 'erabbit' !important;
    content: '\e6cd';
    font-size: 40rpx;
    margin-right: 8rpx;
  }

  .checked::before {
    content: '\e6cc';
    color: #27ba9b;
  }

  .text {
    margin-right: 8rpx;
    margin-left: 32rpx;
    color: #444;
    font-size: 14px;
  }

  .amount {
    font-size: 20px;
    color: #cf4444;

    .decimal {
      font-size: 12px;
    }

    &::before {
      content: '￥';
      font-size: 12px;
    }
  }

  .button-grounp {
    margin-left: auto;
    display: flex;
    justify-content: space-between;
    text-align: center;
    line-height: 72rpx;
    font-size: 13px;
    color: #fff;

    .button {
      width: 240rpx;
      margin: 0 10rpx;
      border-radius: 72rpx;
    }

    .payment-button {
      background-color: #27ba9b;

      &.disabled {
        opacity: 0.6;
      }
    }
  }
}
// 底部占位空盒子
.toolbar-height {
  height: 100rpx;
}
</style>
